<template>
  <div class='cl-switch' @click="handleSwitch" :style="switchStyle">
    <span class="left-txt" v-show="backgroundWord" :style="{color: this.flash && this.act && '#fff'}">{{ tabNames[0] }}</span>
    <span class="right-txt" v-show="backgroundWord">{{ tabNames[1] }}</span>
    <span class="high-btn" :style="highBtnStyle">{{ actName }}</span>
  </div>
</template>

<script type="text/javascript">
export default {
  name: 'Switch',
  props: {
    tabName: {
      type: [Array, String],
      default () {
        return ['关', '开']
      }
    },
    backgroundWord: {
      type: Boolean,
      default: false
    },
    flash: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      act: true
    }
  },
  computed: {
    tabNames () {
      if (typeof this.tabName === 'string') {
        return this.tabName.split(',')
      } else {
        return this.tabName
      }
    },
    actName () {
      return this.act ? this.tabNames[1] : this.tabNames[0]
    },
    highBtnStyle () {
      let len = this.tabNames[0].length
      return {
        width: 10 * len + 14 + 'px',
        left: this.act ? 10 * len + 14 + 'px' : '0px',
        color: this.flash && this.act ? '#3083F2' : this.flash ? '#b6b6b9' : '#EAEBF0',
        'background-color': this.flash ? '#fff' : '#3083F2'
      }
    },
    switchStyle () {
      let len = this.tabNames[0].length
      return {
        width: (10 * len + 14) * 2 + 6 + 'px',
        'background-color': this.flash && this.act ? '#3083F2' : '#EAEBF0'
      }
    }
  },
  methods: {
    handleSwitch () {
      this.act = !this.act
      if (this.act) {
        this.$emit('fn-right', 'right')
      } else {
        this.$emit('fn-left', 'left')
      }
    }
  }
}
</script>

<style lang="scss" type="text/css">
.cl-switch {
  position: relative;
  width: 54px;
  height: 30px;
  color: #878A92;
  font-size: 12px;
  text-align: left;
  line-height: 30px;
  border-radius: 15px;
  background-color: #EAEBF0;
  cursor: pointer;
  transition: background 0.5s;
  .left-txt {
    padding-left: 9px;
  }
  .right-txt {
    float: right;
    padding-right: 8px;
  }
  .high-btn {
    position: absolute;
    left: 0;
    top: 0;
    display: block;
    width: 24px;
    height: 24px;
    margin: 3px;
    color: #fff;
    text-align: center;
    line-height: 24px;
    border-radius: 12px;
    background-color: #3083F2;
    box-shadow: 0 2px 4px RGBA(48, 131, 242, 0.42);
    transition: all 0.5s;
  }
}
</style>
